package com.booklove.service.delivery;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.booklove.domain.dto.PageDTO;
import com.booklove.domain.po.Deliver;
import com.booklove.domain.query.DeliverQuery;
import com.booklove.domain.vo.DeliverVO;
import com.booklove.enumeration.OperationType;
import com.booklove.mapper.DeliverMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booklove.utils.TimeFillUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 派送任务 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-22
 */
@Service
public class DeliverServiceImpl extends ServiceImpl<DeliverMapper, Deliver> implements DeliverService {

    @Autowired
    private DeliverMapper deliverMapper;

    @Override
    public PageDTO<DeliverVO> queryDeliversPage(DeliverQuery deliverQuery) {
        // 1.添加排序规则
        // 使用内置的函数转换并且 设置规则
        List<OrderItem> orderItems = deliverQuery.toMpOrderItems();

        // 获取分页对象和排序情况
        Page<Deliver> page = deliverQuery.toMpPageDefaultSortByIdAsc(orderItems.toArray(new OrderItem[0]));
        /*
        查询
         */
        Page<DeliverVO> p = baseMapper.selectPageVO(page, deliverQuery.getName());

        // 获取数据信息
        return PageDTO.of(p, DeliverVO.class);
    }

    @Override
    public Deliver createDeliver(Integer deliverType, Integer deliverState, Integer startAddressId, Integer endAddressId) {
        Deliver deliver = new Deliver();
        // 补充时间
        deliver = TimeFillUtil.fillTimeAndCreateUser(deliver, OperationType.INSERT);
        deliver.setDeliverType(deliverType);
        deliver.setDeliverState(deliverState);
        deliver.setAddressStartId(startAddressId); // 允许不需要出发点，只用填写null即可
        deliver.setAddressEndId(endAddressId);
        deliverMapper.insert(deliver);
        return deliver;
    }

}
